/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void inorder(TreeNode* root, string& str)
    {
        if (str.size() == 0)
        {
            str += (to_string(root->val));
        }
        else
        {
            str.push_back('(');
            str += (to_string(root->val));
        }
        if (root->left && root->right)
        {
            inorder(root->left, str);
            str.push_back(')');
            inorder(root->right, str);
            str.push_back(')');
        }
        else if (root->left != nullptr && root->right == nullptr)
        {
            inorder(root->left, str);
            str.push_back(')');
        }
        else if (root->left == nullptr && root->right != nullptr)
        {
            str += "()";
            inorder(root->right, str);
            str.push_back(')');
        }
        else if (root->left == nullptr && root->right == nullptr)
        {
            return;
        }
    }
    string tree2str(TreeNode* root) {
        string str;
        inorder(root, str);
        return str;
    }
};